package server.valves;

import server.Context;
import server.Request;
import server.Response;
import server.ValveContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
Host容器的阀,错误转发处理器,如果请求处理出错且给该错误状态码配备转发uri,将使用该处理器将请求转发到新的uri上
*/
/*
2023/3/24 该类内容全部写完,后续直接使用,无需修改
by cyl
 */
public class ErrorDispatcherValve extends ValveBase {
    @Override
    public void invoke(Request request, Response response, ValveContext context) throws IOException, ServletException {
        context.invokeNext(request, response);

        HttpServletRequest hrequest = (HttpServletRequest)(request.getRequest());
        HttpServletResponse hresponse = (HttpServletResponse)(response.getResponse());
        int status = hresponse.getStatus();
        //正常状态码不用调整
        if (status < 400)
            return;

        sendErrorPage(status, request, response);
    }

    private void sendErrorPage(int status, Request request, Response response) throws ServletException, IOException {
        Context context = request.getContext();
        if (context == null)
            return;
        //转发地址
        String location = context.findErrorPage(status);
        if (location == null)
            return;
        ((HttpServletResponse)(response.getResponse())).setStatus(HttpServletResponse.SC_OK);
        request.getRequest().getRequestDispatcher(location).forward(request.getRequest(), response.getResponse());
    }

}
